package edu.towson.cosc.cosc455.ryanhoran;

public class LexAnalyzer implements LexicalAnalyzer {
	
	//define accepted tokens as a list to check tokens
	public String[] tags = {"#Start document", "#End document", "#Start head",
			"#End head", "#Start title", "#End title","#Start paragraph", "#End paragraph", "#Start bold", 
			"#End bold", "#Start italics", "#End italics", "#Start list", "#End list", "#Start item", "#End item", 
			"#Start audio", "#End audio", "#newline", "#Start video", "#End video", "#Start define", "#End define", 
			"#name", "#value", "#Start use", "#End use"};
	int index = 0;
	StringBuilder token = new StringBuilder();
	char lexeme;
	boolean isTag;
	
	public void getNextToken() {
		// TODO Auto-generated method stub   *
		/* Identifies what makes up the next *
		 * token and what the actual token   *
		 * is.								 */
		getCharacter();
		globalVar.currenttoken = token.toString();
		if(isTag){
			if(lookupToken()){
				//hooray
			} else{
				error("Token does not exist.");
			} 
		} 
	}

	@Override
	public void getCharacter() {
		// TODO Auto-generated method stub
		if(globalVar.mkd != null){
		lexeme = globalVar.mkd.charAt(index);
		addCharacter();
		if (lexeme == '#'){
			isTag = true;
			lexeme = globalVar.mkd.charAt(index);
			if(lexeme == 's' || lexeme == 'S' || lexeme == 'e' || lexeme == 'E'){
				addCharacter();
				while(!isSpace(String.valueOf(lexeme))){
					lexeme = globalVar.mkd.charAt(index);
					addCharacter();
				} while(!isSpace(String.valueOf(lexeme))){
					lexeme = globalVar.mkd.charAt(index);
					addCharacter();
				}
			} else{
				isTag = false;
				while(!isSpace(String.valueOf(lexeme))){
					lexeme = globalVar.mkd.charAt(index);
					addCharacter();
				}
			}
		} else {
			while(globalVar.mkd.charAt(index + 1) == '#'){
				lexeme = globalVar.mkd.charAt(index);
				addCharacter();
			}
		}
		} else{
			error("Markdown is null. ");
		}
		
	}

	@Override
	public void addCharacter() {
		// TODO Auto-generated method stub
		token.append(lexeme);
		index++;
	}

	@Override
	public boolean isSpace(String c) {
		// TODO Auto-generated method stub
		if(c.equals(" ")){
			return true;
		} else{
			return false;
		}
	}
		

	@Override
	public boolean lookupToken() {
		// TODO Auto-generated method stub
		for(int j = 0; j < tags.length; j++){
			if (tags[j].equalsIgnoreCase(globalVar.currenttoken)){
				return true;
			}
		}		
		return false;
	}
	
	//Exception Handling
	public void error(String message){
		System.out.printf("Error in Lexical. %n%s%n Program Closing.", message);
		System.exit(0);
	}
}
